package com.example.fund.updatestategy;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.json.JSONObject;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;

import com.example.fund.util.DBManager;
import com.example.fund.util.StringUtil;

public class FundNetValueUpdateStrategy extends AbstractUpdateStrategy {

	private static final String  actualValuesURL = "http://fund.eastmoney.com/f10/F10DataApi.aspx?type=lsjz&code=number&page=pageV&per=10000&sdate=2001-09-21&edate=dateto";
	
	public FundNetValueUpdateStrategy(String number) {
		super(number);
	}

	@Override
	public boolean isNeedUpdate() {
		if(number==null || number.trim().length()==0)
		{
			return false;
		}
		
		SQLiteDatabase db = DBManager.getDB();

		String sql = "select max(date) date from FundNetValue where fundnumber='"+number+"'";
		Cursor c = db.rawQuery(sql, null);
		String date = null;
		if (c.moveToNext())
		{
            date = c.getString(c.getColumnIndex("date"));
		}
		c.close();
		
        if(date==null || date.trim().length()==0)
        {
        	return true;
        }
        
		String sql1 = "select max(date) date from FundNetValue where fundnumber='0000001'";
		Cursor c1 = db.rawQuery(sql1, null);
		String date1 = null;
		if (c1.moveToNext())
		{
            date1 = c1.getString(c1.getColumnIndex("date"));
		}
		c1.close();
		
        if(date1==null || date1.trim().length()==0)
        {
        	return true;
        }
        
        if(date1.compareTo(date)>0)
        {
        	return true;
        }
        
        return false;
	}
	
	
	@Override
	public void updateIndex() {
		SQLiteDatabase db = DBManager.getDB();

		String maxDate = getFundMaxDate();

		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String dateStr = df.format(new Date());
		String dataURL = actualValuesURL.replace("dateto", dateStr).replace("number", number);
		String adataURL = dataURL.replace("pageV","1");
		//获取总页数
		//1.从网络下载。然后截取成XML格式
		SAXReader sax = new SAXReader();
		InputStream inputStream = null;
		Document xmlDoc = null;
		HttpURLConnection con = null;
		BufferedReader reader = null;
		URL url = null;
		String s = null;
		String insertSql = "insert into FundNetValue(id,fundNumber,netValue,date) values (null,?,?,?)";
		SQLiteStatement stmt = db.compileStatement(insertSql);
		db.beginTransaction();
		try
		{
			url = new URL(adataURL);
			con = (HttpURLConnection) url.openConnection();
			con.setRequestMethod("GET");
			reader = new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));
			s = reader.readLine();
			s = s.substring(s.indexOf("{"), s.lastIndexOf("}")+1);
			s = s.replace("content","\"content\"").replace("records","\"records\"").replace("pages","\"pages\"").replace("curpage","\"curpage\"");
			JSONObject json = new JSONObject(s);
			int pages = json.getInt("pages");
			BigDecimal netValue = BigDecimal.ONE;
			String lastNetValue = "1";
			for (int i = pages;i>=1;i--)
			{
				adataURL = dataURL.replace("pageV",""+i);
				url = new URL(adataURL);
				con = (HttpURLConnection) url.openConnection();
				con.setRequestMethod("GET");
				reader = new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));
				s = reader.readLine();
				s = s.substring(s.indexOf("{"), s.lastIndexOf("}")+1);
				s = s.replace("content","\"content\"").replace("records","\"records\"").replace("pages","\"pages\"").replace("curpage","\"curpage\"");
				json = new JSONObject(s);
				s = json.getString("content");
				inputStream = new ByteArrayInputStream(s.getBytes("UTF-8"));
				xmlDoc = sax.read(inputStream);

				Element table = xmlDoc.getRootElement();//根节点
				Element tbody = (Element)table.element("tbody");
				List trs = tbody.elements("tr");

				for(int j=trs.size()-1;j>=0;j--)
				{
					Element tr = (Element)trs.get(j);
					List tds = tr.elements("td");
					if(tds.size()<7)
					{
						continue;
					}
					String enddate = ((Element)tds.get(0)).getTextTrim();
					String unitnetvalue = ((Element)tds.get(1)).getTextTrim();
					String redStr = ((Element)tds.get(6)).getTextTrim();
					Pattern pattern = Pattern.compile("金(.*)元");
					Matcher matcher = pattern.matcher(redStr);
					String redValue = null;
					if(matcher.find())
					{
						redValue = matcher.group(1).trim();
					}
					Pattern pattern1 = Pattern.compile("折算(.*)份");
					Matcher matcher1 = pattern1.matcher(redStr);
					String convertValue = null;
					if(matcher1.find())
					{
						convertValue = matcher1.group(1).trim();
					}
					Pattern pattern2 = Pattern.compile("分拆(.*)份");
					Matcher matcher2 = pattern2.matcher(redStr);
					String convertValue2 = null;
					if(matcher2.find())
					{
						convertValue2 = matcher2.group(1).trim();
					}

					if(enddate!=null && enddate.trim().length()>0 && unitnetvalue!=null && unitnetvalue.trim().length()>0
							&& lastNetValue!=null && lastNetValue.trim().length()>0)
					{
						BigDecimal rise = null;
						BigDecimal blastNetValue = new BigDecimal(lastNetValue);
						if(redValue!=null && redValue.trim().length()>0)
						{
							rise = new BigDecimal(unitnetvalue).add(new BigDecimal(redValue)).subtract(blastNetValue).divide(blastNetValue, 10, RoundingMode.HALF_UP);
						}else if(convertValue!=null && convertValue.trim().length()>0)
						{
							rise = new BigDecimal(unitnetvalue).multiply(new BigDecimal(convertValue)).subtract(blastNetValue).divide(blastNetValue, 10, RoundingMode.HALF_UP);
						}else if(convertValue2!=null && convertValue2.trim().length()>0)
						{
							rise = new BigDecimal(unitnetvalue).multiply(new BigDecimal(convertValue2)).subtract(blastNetValue).divide(blastNetValue, 10, RoundingMode.HALF_UP);
						}else
						{
							rise = new BigDecimal(unitnetvalue).subtract(blastNetValue).divide(blastNetValue, 10, RoundingMode.HALF_UP);
						}
						netValue = netValue.multiply(BigDecimal.ONE.add(rise)).setScale(5,BigDecimal.ROUND_HALF_UP);

						if(maxDate==null || maxDate.trim().length()==0 || enddate.compareTo(maxDate)>0)
						{
							stmt.bindString(1, number);
							stmt.bindDouble(2, netValue.doubleValue());
							stmt.bindString(3, enddate);
							stmt.execute();
							stmt.clearBindings();
						}
					}
					lastNetValue = unitnetvalue;
				}
			}
			db.setTransactionSuccessful();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			if(reader!=null)
			{
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(con!=null)
			{
				con.disconnect();
			}
			db.endTransaction();
		}
	}

}
